// 页面加载时获取统计信息
window.onload = function() {
    refreshStats();
    loadLoggers();

    // 为处理器表单添加事件监听器
    document.getElementById('handler-form').addEventListener('submit', function(e) {
        e.preventDefault();
        addHandler();
    });

    // 处理器类型变化事件
    document.getElementById('handler-type').addEventListener('change', function() {
        const type = this.value;
        const fileOptions = document.querySelectorAll('.file-options');
        if (type === 'file') {
            fileOptions.forEach(option => option.style.display = 'block');
        } else {
            fileOptions.forEach(option => option.style.display = 'none');
        }
    });
};

// 刷新统计信息
function refreshStats() {
    fetch('/logs/stats')
        .then(response => response.json())
        .then(data => {
            if (data.msg === 'ok') {
                document.getElementById('debug-count').textContent = data.data.DEBUG;
                document.getElementById('info-count').textContent = data.data.INFO;
                document.getElementById('warning-count').textContent = data.data.WARNING;
                document.getElementById('error-count').textContent = data.data.ERROR;
                document.getElementById('critical-count').textContent = data.data.CRITICAL;
            }
        })
        .catch(error => {
            console.error('获取统计信息失败:', error);
        });
}

// 重置统计信息
function resetStats() {
    if (confirm('确定要重置统计信息吗？')) {
        fetch('/logs/stats', {method: 'DELETE'})
            .then(response => response.json())
            .then(data => {
                if (data.msg === 'ok') {
                    refreshStats();
                    alert('统计信息已重置');
                }
            })
            .catch(error => {
                console.error('重置统计信息失败:', error);
            });
    }
}

// 加载Logger列表
function loadLoggers() {
    fetch('/logs/loggers')
        .then(response => response.json())
        .then(data => {
            if (data.msg === 'ok') {
                displayLoggers(data.data);
            }
        })
        .catch(error => {
            console.error('获取Logger列表失败:', error);
        });
}

// 显示Logger列表
function displayLoggers(loggerNames) {
    const loggerList = document.getElementById('logger-list');
    loggerList.innerHTML = '';

    loggerNames.forEach(name => {
        const loggerDiv = document.createElement('div');
        loggerDiv.className = 'logger-item';
        loggerDiv.innerHTML = `
            <div class="logger-header">
                <div class="logger-name">${name}</div>
                <div class="logger-controls">
                    <button onclick="showLoggerDetails('${name}')">详情</button>
                    <select onchange="changeLogLevel('${name}', this.value)">
                        <option value="">设置级别</option>
                        <option value="DEBUG">DEBUG</option>
                        <option value="INFO">INFO</option>
                        <option value="WARNING">WARNING</option>
                        <option value="ERROR">ERROR</option>
                        <option value="CRITICAL">CRITICAL</option>
                    </select>
                    <select onchange="changePropagate('${name}', this.value)">
                        <option value="">传播</option>
                        <option value="true">是</option>
                        <option value="false">否</option>
                    </select>
                    <button onclick="showAddHandlerModal('${name}')">添加处理器</button>
                </div>
            </div>
            <div class="logger-details hidden" id="details-${name}"></div>
        `;
        loggerList.appendChild(loggerDiv);
    });
}

// 显示Logger详情
function showLoggerDetails(loggerName) {
    const detailsDiv = document.getElementById(`details-${loggerName}`);
    if (detailsDiv.classList.contains('hidden')) {
        fetch(`/logs/loggers/${loggerName}`)
            .then(response => response.json())
            .then(data => {
                if (data.msg === 'ok') {
                    const info = data.data;
                    let handlersHtml = '';
                    if (info.handlers && info.handlers.length > 0) {
                        handlersHtml = '<div class="handler-list">';
                        info.handlers.forEach((handler, index) => {
                            handlersHtml += `
                                <div class="handler-item">
                                    <div>
                                        <strong>类型:</strong> ${handler.type}
                                        <br>
                                        <strong>级别:</strong> ${handler.level}
                                        <br>
                                        <strong>格式:</strong> ${handler.formatter}
                                        ${handler.name ? `<br><strong>名称:</strong> ${handler.name}` : ''}
                                        ${handler.filename ? `<br><strong>文件名:</strong> ${handler.filename}` : ''}
                                        ${handler.max_bytes ? `<br><strong>最大字节数:</strong> ${handler.max_bytes}` : ''}
                                        ${handler.backup_count ? `<br><strong>备份数量:</strong> ${handler.backup_count}` : ''}

                                        <!-- 显示过滤器信息 -->
                                        ${handler.filters && handler.filters.length > 0 ? `
                                            <br><strong>过滤器:</strong>
                                            ${handler.filters.map(filter => `
                                                <div style="margin-left: 10px;">
                                                    <strong>类型:</strong> ${filter.type}
                                                    ${filter.min_level ? `<br><strong>最小级别:</strong> ${filter.min_level}` : ''}
                                                    ${filter.max_level ? `<br><strong>最大级别:</strong> ${filter.max_level}` : ''}
                                                    ${filter.include_keywords && filter.include_keywords.length > 0 ? `<br><strong>包含关键词:</strong> ${filter.include_keywords.join(', ')}` : ''}
                                                    ${filter.exclude_keywords && filter.exclude_keywords.length > 0 ? `<br><strong>排除关键词:</strong> ${filter.exclude_keywords.join(', ')}` : ''}
                                                </div>
                                            `).join('')}
                                        ` : ''}
                                    </div>
                                    <button class="danger" onclick="removeHandler('${loggerName}', ${index})">移除</button>
                                </div>
                            `;
                        });
                        handlersHtml += '</div>';
                    } else {
                        handlersHtml = '<p>没有处理器</p>';
                    }

                    detailsDiv.innerHTML = `
                        <p><strong>级别:</strong> ${info.level}</p>
                        <p><strong>有效级别:</strong> ${info.effective_level}</p>
                        <p><strong>传播:</strong> ${info.propagate ? '是' : '否'}</p>
                        <p><strong>处理器:</strong></p>
                        ${handlersHtml}
                    `;
                    detailsDiv.classList.remove('hidden');
                }
            })
            .catch(error => {
                console.error('获取Logger详情失败:', error);
            });
    } else {
        detailsDiv.classList.add('hidden');
    }
}

// 更改Logger级别
function changeLogLevel(loggerName, level) {
    if (level === '') return;

    fetch(`/logs/loggers/${loggerName}/config`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({level: level})
    })
    .then(response => response.json())
    .then(data => {
        if (data.msg === 'ok') {
            alert(`Logger ${loggerName} 的级别已设置为 ${level}`);
            // 刷新详情以显示更改
            showLoggerDetails(loggerName);
        } else {
            alert('设置失败: ' + data.detail);
        }
    })
    .catch(error => {
        console.error('设置Logger级别失败:', error);
        alert('设置失败: ' + error.message);
    });
}

// 更改Logger传播属性
function changePropagate(loggerName, propagate) {
    if (propagate === '') return;

    fetch(`/logs/loggers/${loggerName}/config`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({propagate: propagate})
    })
    .then(response => response.json())
    .then(data => {
        if (data.msg === 'ok') {
            alert(`Logger ${loggerName} 的传播属性已设置为 ${propagate}`);
            // 刷新详情以显示更改
            showLoggerDetails(loggerName);
        } else {
            alert('设置失败: ' + data.detail);
        }
    })
    .catch(error => {
        console.error('设置Logger传播属性失败:', error);
        alert('设置失败: ' + error.message);
    });
}

// 显示添加处理器模态框
function showAddHandlerModal(loggerName) {
    document.getElementById('handler-logger-name').value = loggerName;
    document.getElementById('handler-modal').classList.remove('hidden');
}

// 关闭添加处理器模态框
function closeHandlerModal() {
    document.getElementById('handler-modal').classList.add('hidden');
}

// 添加处理器
function addHandler() {
    const loggerName = document.getElementById('handler-logger-name').value;
    const type = document.getElementById('handler-type').value;
    const level = document.getElementById('handler-level').value;
    const format = document.getElementById('handler-format').value;

    const handlerConfig = {
        type: type,
        level: level,
        format: format
    };

    if (type === 'file') {
        handlerConfig.filename = document.getElementById('handler-filename').value;
        handlerConfig.max_bytes = parseInt(document.getElementById('handler-max-bytes').value);
        handlerConfig.backup_count = parseInt(document.getElementById('handler-backup-count').value);
    }

    fetch(`/logs/loggers/${loggerName}/handlers`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(handlerConfig)
    })
    .then(response => response.json())
    .then(data => {
        if (data.msg === 'ok') {
            alert(data.message);
            closeHandlerModal();
            showLoggerDetails(loggerName); // 刷新详情
        } else {
            alert('添加失败: ' + data.detail);
        }
    })
    .catch(error => {
        console.error('添加处理器失败:', error);
        alert('添加失败: ' + error.message);
    });
}

// 移除处理器
function removeHandler(loggerName, handlerIndex) {
    if (!confirm(`确定要移除处理器 ${handlerIndex} 吗？`)) {
        return;
    }

    fetch(`/logs/loggers/${loggerName}/handlers/${handlerIndex}`, {
        method: 'DELETE'
    })
    .then(response => response.json())
    .then(data => {
        if (data.msg === 'ok') {
            alert(data.message);
            showLoggerDetails(loggerName); // 刷新详情
        } else {
            alert('移除失败: ' + data.detail);
        }
    })
    .catch(error => {
        console.error('移除处理器失败:', error);
        alert('移除失败: ' + error.message);
    });
}

// 过滤Logger
function filterLoggers() {
    const searchTerm = document.getElementById('logger-search').value.toLowerCase();
    const loggerItems = document.querySelectorAll('.logger-item');

    loggerItems.forEach(item => {
        const loggerName = item.querySelector('.logger-name').textContent.toLowerCase();
        if (loggerName.includes(searchTerm)) {
            item.style.display = '';
        } else {
            item.style.display = 'none';
        }
    });
}

// 定期刷新统计信息
setInterval(refreshStats, 5000);
